import React, { Component } from 'react'
import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {BASE_ULR} from "../../config/index"
import {reqDeletePicture} from "../../api"

//把图片编程base64编码形式
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class PicturesWall extends Component {
  state = {
    previewVisible: false, //是否展示预览窗口
    previewImage: '',  //要预览的图片的URL地址或者base64编码
    previewTitle: '',
    fileList: [
      // {
      //   uid: '-1',
      //   name: 'image.png',
      //   status: 'done',   //当前图片的状态：uploading(上传中)、done、removed、error
      //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      // }
    ],
  };
  //关闭预览窗口
  handleCancel = () => this.setState({ previewVisible: false });
  //展示与蓝窗
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  //当图片状态发生改变时
  handleChange = async({ file,fileList }) => {
    if(file.status === "done") {
      fileList[fileList.length - 1].url = file.response.data.url
      fileList[fileList.length - 1].name = file.response.data.name
    }
    if(file.status === "removed") {
      let result =await reqDeletePicture(file.name)
      const {status} = result
      if(status === 0) message.success('删除图片成功')
      else message.error('删除图片失败')
    }
    this.setState({ fileList })
  }

  //获取照片数组
  getImgArr = ()=>{
    let imgArr = []
    this.state.fileList.forEach((item)=>{
      imgArr.push(item.name)
    })
    return imgArr
  }
  //设置一个图片文件列表
  setFileList = (imgArr)=>{
    let fileList = []
    imgArr.forEach((item,index)=>{
      fileList.push({uid:-index,name:item,url:`${BASE_ULR}/upload/${item}`})
    })
    this.setState({fileList})
  }

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action={`${BASE_ULR}/manage/img/upload`}   //【注意】接受图片的服务器的地址
          name="image"   //【注意】发到后台的文件参数名

          listType="picture-card"  //控制照片墙的展示方式
          fileList={fileList}   //图片列表，一个数组里面包含着多个图片对象{uid:xxxxx，name:xxxx, status:xxxx, url:xxxxx}
          onPreview={this.handlePreview}  //点击预览按钮的回调
          onChange={this.handleChange}  //图片状态改变的回调（图片上传中、图片被删除、图片成功上传）
        >
        {/*隐藏上传按钮的图片数量的阈值*/}
          {fileList.length >= 8 ? null : uploadButton} 
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}
